package com.crm.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.crm.dao.UserDAO;
import com.crm.po.Users;
import com.crm.util.RequestEx;
import com.crm.util.SESSION;

public class UserService {
	
	private static Logger logger = Logger.getLogger(UserService.class);
	
	public String exeLogin(HttpServletRequest request){
		Object result = null;
		Users users = null;
		try{
			String username = RequestEx.getStringTrim(request.getParameter("username"));
			String pwd = RequestEx.getStringTrim(request.getParameter("pwd"));
			if(username.length() > 0 && pwd.length() > 0){
				String hql = "from Users T WHERE T.username = '" + username + "' and T.pwd = '" + pwd + "'";
				UserDAO dao = new UserDAO();
				result = dao.getUniqueResult(hql);
				if(result != null){
					users = (Users)result;
					if("Y".equalsIgnoreCase(users.getIslive())){
						request.getSession(true).setAttribute(SESSION.USER_SESSION_KEY, users);
						return "ok";
					}else{
						return "该用户已被停用，如有疑问请联系管理员。";
					}
				}
			}			
		}catch(Exception e){
			logger.error("login error:", e);
			return "登录出现错误，请检查您的系统。";
		}
		return "用户名称或密码不正确。";
	}
	
	public Map<String, Object> getUsers(HttpServletRequest request){
		StringBuffer Hql = new StringBuffer(" from Users t where 1=1 ");
		int page = Integer.parseInt(request.getParameter("page"));//当前第几页
		int rows = Integer.parseInt(request.getParameter("rows"));//每页显示几行
		
		UserDAO dao = new UserDAO();
		String countHql = "select count(t.uid) " + Hql.toString();
		int count = dao.getCount(countHql);
		Hql.append(" order by t.sort, t.username ");
	    List<Users> list = dao.usersListPage(Hql.toString(), (page-1) * rows, rows);
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("count", count);
	    map.put("rows", list);
	    return map;
	} 
	
	public int saveOrUpdateUsers(HttpServletRequest request){
		try{
			String uid = RequestEx.getStringTrim(request.getParameter("uid"));
			String username = RequestEx.getStringTrim(request.getParameter("username"));
			String pwd = RequestEx.getStringTrim(request.getParameter("pwd"));
			String nickname = RequestEx.getStringTrim(request.getParameter("nickname"));
			String tel = RequestEx.getStringTrim(request.getParameter("tel"));
			String phone = RequestEx.getStringTrim(request.getParameter("phone"));
			String email = RequestEx.getStringTrim(request.getParameter("email"));
			String sex = RequestEx.getStringTrim(request.getParameter("sex"), "男");
			String job = RequestEx.getStringTrim(request.getParameter("job"));
			
			String cusAuth = RequestEx.getCheckBox(request.getParameterValues("cusAuth"), ",");
			String invAuth = RequestEx.getCheckBox(request.getParameterValues("invAuth"), ",");
			String invppAuth = RequestEx.getCheckBox(request.getParameterValues("invppAuth"), ",");
			String buyAuth = RequestEx.getCheckBox(request.getParameterValues("buyAuth"), ",");
			String kcAuth = RequestEx.getCheckBox(request.getParameterValues("kcAuth"), ",");
			String fp1Auth = RequestEx.getCheckBox(request.getParameterValues("fp1Auth"), ",");
			String fp2Auth = RequestEx.getCheckBox(request.getParameterValues("fp2Auth"), ",");
			String incomeAuth = RequestEx.getCheckBox(request.getParameterValues("incomeAuth"), ",");
			String offerAuth = RequestEx.getCheckBox(request.getParameterValues("offerAuth"), ",");
			
			
			String islive = RequestEx.getStringTrim(request.getParameter("islive"), "Y");
			
			UserDAO dao = new UserDAO();
			Users users = null;
			if(uid != null && uid.trim().length() > 0){
				//修改
				int count = dao.getCount("select count(T.uid) from Users T where T.username = '" + username + "' and T.uid <> '" + uid + "'");
				if(count > 0){
					return -1;
				}
				users = dao.findById(uid);
			}else{
				//新增
				int count = dao.getCount("select count(T.uid) from Users T where T.username = '" + username + "'");
				if(count > 0){
					return -1;
				}
				users = new Users();
				users.setSort(99);
			}

			users.setUsername(username);
			users.setPwd(pwd);
			users.setNickname(nickname);
			users.setTel(tel);
			users.setPhone(phone);
			users.setEmail(email);
			users.setSex(sex);
			users.setJob(job);
			users.setIslive(islive);
			
			users.setCusAuth(cusAuth);
			users.setInvAuth(invAuth);
			users.setInvppAuth(invppAuth);
			users.setBuyAuth(buyAuth);
			users.setKcAuth(kcAuth);
			users.setFp1Auth(fp1Auth);
			users.setFp2Auth(fp2Auth);
			users.setIncomeAuth(incomeAuth);
			users.setOfferAuth(offerAuth);
	
			dao.saveOrUpdate(users);
		}catch(Exception e){
			logger.error("save or update user fail:", e);
			return 0;
		}
	    return 1;
	}
	
	public boolean closeUsers(HttpServletRequest request){
		int result = 0;
		try{
			String uids = RequestEx.getStringTrim(request.getParameter("uids"));
			if(uids.length() > 0){
				String hql = "UPDATE Users T SET T.islive = 'N' WHERE T.uid IN (" + uids + ")";
				UserDAO dao = new UserDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("close user fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean openUsers(HttpServletRequest request){
		int result = 0;
		try{
			String uids = RequestEx.getStringTrim(request.getParameter("uids"));
			if(uids.length() > 0){
				String hql = "UPDATE Users T SET T.islive = 'Y' WHERE T.uid IN (" + uids + ")";
				UserDAO dao = new UserDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("open user fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean deleteUsers(HttpServletRequest request){
		int result = 0;
		try{
			String uids = RequestEx.getStringTrim(request.getParameter("uids"));
			if(uids.length() > 0){
				String hql = "DELETE FROM Users T WHERE T.uid IN (" + uids + ")";
				UserDAO dao = new UserDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete user fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public Users getUsersById(HttpServletRequest request){
		Users users = null;
		try{
			String uid = RequestEx.getStringTrim(request.getParameter("uid"));
			if(uid.length() > 0){
				UserDAO dao = new UserDAO();
				users = dao.findById(uid);
			}			
		}catch(Exception e){
			logger.error("select user by uid fail:", e);
			return null;
		}
	    return users;
	}
	
	public boolean updateSelfInfo(HttpServletRequest request){
		try{
			String uid = RequestEx.getStringTrim(request.getParameter("uid"));
			String pwd = RequestEx.getStringTrim(request.getParameter("pwd"));
			String nickname = RequestEx.getStringTrim(request.getParameter("nickname"));
			String tel = RequestEx.getStringTrim(request.getParameter("tel"));
			String phone = RequestEx.getStringTrim(request.getParameter("phone"));
			String email = RequestEx.getStringTrim(request.getParameter("email"));
			String sex = RequestEx.getStringTrim(request.getParameter("sex"));
			
			UserDAO dao = new UserDAO();
			Users users = dao.findById(uid);

			users.setPwd(pwd);
			users.setNickname(nickname);
			users.setTel(tel);
			users.setPhone(phone);
			users.setEmail(email);
			users.setSex(sex);
	
			dao.saveOrUpdate(users);
		}catch(Exception e){
			logger.error("update self info fail:", e);
			return false;
		}
	    return true;
	}
	
}
